using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using ContentmanagementBase.Domain;
using ContentmanagementBaseWrite.API.Applications.Commands.Questions;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace ContentmanagementBaseWrite.API.Applications.Commandhandlters.Questions
{
    /// <summary>
    /// 批量逻辑删除常见问题命令处理
    /// </summary>
    public class BatchDeleteProblemCommandHandler : IRequestHandler<BatchDeleteProblemCommand, ApiResult<bool>>
    {
        /// <summary>
        /// 问题仓储
        /// </summary>
        private readonly IBaseRepository<ProblemManagementModel> _problemRepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<BatchDeleteProblemCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="problemRepository">问题仓储</param>
        /// <param name="logger">日志</param>
        public BatchDeleteProblemCommandHandler(
            IBaseRepository<ProblemManagementModel> problemRepository,
            ILogger<BatchDeleteProblemCommandHandler> logger)
        {
            _problemRepository = problemRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理批量删除常见问题命令
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns></returns>
        public async Task<ApiResult<bool>> Handle(BatchDeleteProblemCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 验证输入参数
                if (request.Ids == null || !request.Ids.Any())
                {
                    return new ApiResult<bool>
                    {
                        code = ResultEnumCode.fails,
                        message = "问题编号列表不能为空",
                        data = false
                    };
                }

                // 验证ID列表中的每个ID是否有效
                if (request.Ids.Any(id => id <= 0))
                {
                    return new ApiResult<bool>
                    {
                        code = ResultEnumCode.fails,
                        message = "问题编号必须大于0",
                        data = false
                    };
                }

                _logger.LogInformation("开始处理批量删除常见问题命令，问题数量：{Count}，ID列表：{@Ids}", 
                    request.Ids.Count, request.Ids);

                // 查找要删除的问题
                var problemsToDelete = await _problemRepository.GetAll()
                    .Where(x => request.Ids.Contains(x.Id))
                    .ToListAsync(cancellationToken);

                if (problemsToDelete.Count == 0)
                {
                    _logger.LogWarning("未找到任何匹配的常见问题进行删除，ID列表：{@Ids}", request.Ids);
                    return new ApiResult<bool>
                    {
                        code = ResultEnumCode.fails,
                        message = "未找到任何匹配的常见问题进行删除",
                        data = false
                    };
                }

                // 检查是否有ID不存在
                var foundIds = problemsToDelete.Select(x => x.Id).ToList();
                var notFoundIds = request.Ids.Except(foundIds).ToList();
                
                if (notFoundIds.Any())
                {
                    _logger.LogWarning("部分问题ID不存在：{@NotFoundIds}", notFoundIds);
                }

                _logger.LogInformation("找到 {Found} 个问题进行删除，未找到 {NotFound} 个问题", 
                    problemsToDelete.Count, notFoundIds.Count);

                // 执行逻辑删除
                foreach (var problem in problemsToDelete)
                {
                    problem.IsDeleted = true;
                    problem.UpdatedTime = DateTime.Now;
                    problem.UpdatedBy = 1; // 这里应该从当前用户上下文获取
                   
                }

                _logger.LogInformation("开始批量保存删除标记到数据库");
                var result = await _problemRepository.UpdateRanger(problemsToDelete);
                _logger.LogInformation("批量删除完成，影响行数：{Result}", result);

                if (result > 0)
                {
                    var deletedCount = problemsToDelete.Count;
                    var message = notFoundIds.Any() 
                        ? $"成功删除 {deletedCount} 个常见问题，{notFoundIds.Count} 个问题不存在"
                        : $"成功删除 {deletedCount} 个常见问题";

                    _logger.LogInformation("常见问题批量删除成功，删除数量：{Count}", deletedCount);
                    return new ApiResult<bool>
                    {
                        code = ResultEnumCode.Ok,
                        message = message,
                        data = true
                    };
                }
                else
                {
                    _logger.LogWarning("常见问题批量删除失败，数据库未返回影响行数");
                    return new ApiResult<bool>
                    {
                        code = ResultEnumCode.fails,
                        message = "常见问题批量删除失败",
                        data = false
                    };
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "常见问题批量删除过程中发生异常，ID列表：{@Ids}", request.Ids);
                return new ApiResult<bool>
                {
                    code = ResultEnumCode.fails,
                    message = $"常见问题批量删除异常：{ex.Message}",
                    data = false
                };
            }
        }
    }
}